package cn.wolfcode.luowowo.search.service.impl;

import cn.wolfcode.luowowo.search.query.SearchQueryObject;
import cn.wolfcode.luowowo.search.repository.StrategySearchRepository;
import cn.wolfcode.luowowo.search.service.IStrategySearchService;
import cn.wolfcode.luowowo.search.template.StrategyTemplate;
import cn.wolfcode.luowowo.search.vo.StatsResult;
import org.apache.dubbo.config.annotation.Service;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.bucket.composite.CompositeAggregation;
import org.elasticsearch.search.aggregations.bucket.composite.CompositeAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.composite.CompositeValuesSourceBuilder;
import org.elasticsearch.search.aggregations.bucket.composite.TermsValuesSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;

import java.util.*;

@Service
public class StrategySearchServiceImpl implements IStrategySearchService {
    @Autowired
    private StrategySearchRepository repository;

    public void save(StrategyTemplate template) {
        repository.save(template);
    }


    //桶聚合多维度查询
    public List<StatsResult> groupCondition(String id, String name, int condition) {
        String groupType = "groupType";
        String idField = "id";
        String nameField = "name";

        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        builder.withPageable(PageRequest.of(0, 1));
        switch (condition) {
            case SearchQueryObject.CONDITION_UNABROAD:
                //CONDITION_UNABROAD->排除非中国数据
                builder.withQuery(QueryBuilders.termQuery("countryId", StatsResult.CHINA_ID));
                break;
            case SearchQueryObject.CONDITION_ABROAD:
                //CONDITION_ABROAD->排除中国数据
                builder.withQuery(
                        QueryBuilders.boolQuery()
                                .mustNot(
                                        QueryBuilders.termQuery("countryId", StatsResult.CHINA_ID)
                                )
                );
                break;
        }

        //多维度桶聚合条件
        List<CompositeValuesSourceBuilder<?>> sources = new ArrayList<>();

        sources.add(new TermsValuesSourceBuilder(idField).field(id));
        sources.add(new TermsValuesSourceBuilder(nameField).field(name));

        CompositeAggregationBuilder group = new CompositeAggregationBuilder(groupType, sources);

        builder.addAggregation(group);
        AggregatedPage<StrategyTemplate> page = (AggregatedPage<StrategyTemplate>) repository.search(builder.build());

        //拿到分组结果
        CompositeAggregation aggs = (CompositeAggregation) page.getAggregation(groupType);

        List<StatsResult> list = new ArrayList<>();
        for (CompositeAggregation.Bucket bucket : aggs.getBuckets()) {
            Map<String, Object> key = bucket.getKey();
            Object idValue = key.get(idField);
            Object nameValue = key.get(nameField);
            long count = bucket.getDocCount();
            list.add(new StatsResult(Long.parseLong(idValue.toString()), nameValue.toString(), count));
        }
        return list;
    }

    public List<StatsResult> listCondition(int condition) {
        String id = null;
        String name = null;

        switch (condition) {
            case SearchQueryObject.CONDITION_UNABROAD:
                id = "provinceId";
                name = "provinceName";
                break;
            case SearchQueryObject.CONDITION_ABROAD:
                id = "countryId";
                name = "countryName";
                break;
            case SearchQueryObject.CONDITION_THEME:
                id = "themeId";
                name = "themeName";
                break;
        }
        return groupCondition(id, name, condition);
    }


    public Page<StrategyTemplate> query(SearchQueryObject qo) {
        Page<StrategyTemplate> page = null;

        switch (qo.getType()) {
            case SearchQueryObject.CONDITION_UNABROAD:
                repository.findByProvinceId(qo.getTypeValue(), qo.getPageable());
                break;
            case SearchQueryObject.CONDITION_ABROAD:
                repository.findByCountryId(qo.getTypeValue(), qo.getPageable());
                break;
            case SearchQueryObject.CONDITION_THEME:
                repository.findByThemeId(qo.getTypeValue(), qo.getPageable());
                break;
        }
        return repository.findAll(qo.getPageable());
    }

    //map:{themeName: 1
    //    dests: n     }   map--> list:{map1,map2...}
    public List<Map<String, Object>> themeCommend() {
        List<Map<String, Object>> list = new ArrayList<>();
        //桶聚合拿到主题的统计对象
        List<StatsResult> vos = groupCondition("themeId", "themeName", 0);
        for (StatsResult result : vos) {//主题的统计结果集
            Map<String, Object> map = new HashMap<>();
            map.put("themeName", result.getName());//装入主题名

            Long themeId = result.getId();//主题id
            //根据主题id查询攻略
            List<StrategyTemplate> strategyTemplateList = repository.findByThemeId(themeId, null).getContent();

            Set<StatsResult> dests = new HashSet<>();//底层去重
            for (StrategyTemplate strategyTemplate : strategyTemplateList) {
                StatsResult statsResult = new StatsResult(strategyTemplate.getDestId(), strategyTemplate.getDestName(), null);
                dests.add(statsResult);//把主题的统计对象添加到集合中
            }
            //当前主题关联的所有目的地
            map.put("dests", dests);
            list.add(map);
        }
        return list;
    }

    public List<StrategyTemplate> listByDestName(String keyword) {
        return repository.findByDestName(keyword);
    }
}
